package com.bingxu.flink.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/17 20:09
 * @modifier :
 */

public class OperatorBroadCastState {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",10086);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 设置水印自动抛出的时间周期
//        env.getConfig().setAutoWatermarkInterval(1000);
        env.setParallelism(2);
        env.enableCheckpointing(3000);

        /**
         * 声明两个流进行处理
         * dataStream 数据流
         * controlStream 作为广播流，根据广播流中的数据，改变dataStream中对于数据的处理逻辑
         */
        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> controlStream = env.socketTextStream("localhost", 9898);

        // 1.定义一个广播状态,广播状态本质是一个map集合，并将控制流作为一个广播流
        MapStateDescriptor<String, Integer> broadcastDescripter =
                new MapStateDescriptor<String, Integer>("controlState",String.class,Integer.class);
        BroadcastStream<String> broadcastStream = controlStream.broadcast(broadcastDescripter);

        // 2.将数据流和广播流connect
        dataStream.connect(broadcastStream)
                .process(new BroadcastProcessFunction<String, String, String>() {
                    /**
                     * 处理单个元素的逻辑
                     * @param value
                     * @param ctx
                     * @param out
                     * @throws Exception
                     */
                    @Override
                    public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
                        ReadOnlyBroadcastState<String, Integer> broadcastState = ctx.getBroadcastState(broadcastDescripter);
                        // 获取当前状态下的值
                        Integer controlInfo = broadcastState.get("switch");
                        System.out.println("controlInfo = " + controlInfo);
                        if ("1".equals(controlInfo.toString())) {
                            out.collect("目前执行1号方案，data="+value);
                        } else if ("3".equals(controlInfo.toString())) {
                            out.collect("将数据存储本地：data=" + value);
                        } else {
                            out.collect("将数据发送kafka：data=" + value);

                        }

                    }

                    /**
                     * 广播控制的流，当有数据进入时进行对应的状态保存
                     * @param value
                     * @param ctx
                     * @param out
                     * @throws Exception
                     */
                    @Override
                    public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
                        BroadcastState<String, Integer> broadcastState = ctx.getBroadcastState(broadcastDescripter);
                        // 保存控制流的状态
                        broadcastState.put("switch",Integer.valueOf(value));
                    }
                }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
